package com.im.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.im.app.manager.UserManager;
import com.im.app.mapper.IUserMapper;
import com.im.app.service.IUserService;
import com.im.app.model.User;
import org.jim.core.cache.redis.JedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class IUserImpl extends ServiceImpl<IUserMapper, User> implements IUserService {

    @Resource
    private IUserMapper iUserMapper;

    @Override
    public boolean updateById(User entity) {
        return super.updateById(entity);
    }

    private void cacheKefuUser(User user){
        if(user == null) return;
        String key = "kefu_"+user.getUserId();
        UserManager.getManager().cacheKefuUser(key,user);
    }

    private User getRedisKefuUser(String key){
        User user = null;
        try {
            user = JedisTemplate.me().get(key, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }


    @Override
    public User getUserByKefuIdAndIp(String kefuId, String ip) {
        return iUserMapper.getUserByKefuIdAndIp(kefuId, ip);
    }


    @Override
    public User getUserByDeviceId(String kefuId, String deviceId) {
        return iUserMapper.getUserByDeviceId(kefuId, deviceId);
    }


    @Override
    public List<User> getUserByKefuId(String kefuId, String date) {
        List<User> users = iUserMapper.getUserByKefuId(kefuId,date);
        return users;
    }

    @Override
    public User getUserBykamiCode(String kamicode) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("kamicode",kamicode);
       return iUserMapper.selectOne(userQueryWrapper);
    }

    @Override
    public User getUserByUserId(String userId) {
        return iUserMapper.selectById(userId);
    }


    @Override
    public int doBlackByUserIdAndIp(String userId ,int status) {
        return iUserMapper.doBlackByUserIdAndIp(userId,status);
    }

    @Override
    public int getTodayVisitor(String userId) {
        return iUserMapper.getTodayVisitor(userId);
    }

//    @Override
//    public List<Map<String,String>> getSumVisitor(String userId) {
//        return iUserMapper.getSumVisitor(userId);
//    }



    @Override
    public User getKefuUser(String userId) {
        String key = "kefu_" + userId;
        User user = getRedisKefuUser(key);
        if(user == null){
            user = iUserMapper.selectById(userId);
            if(user != null){
                cacheKefuUser(user);
            }
        }
        return user;
    }



}
